package org.ljy.forum6.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.ljy.forum6.common.AppConfig;
import org.ljy.forum6.common.AppResult;
import org.ljy.forum6.common.ResultCode;
import org.ljy.forum6.exception.ApplicationException;
import org.ljy.forum6.model.Article;
import org.ljy.forum6.model.User;
import org.ljy.forum6.services.impl.ArticleServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleServiceImpl articleService;


    /**
     *  发布新帖子
     * @param request 用户获取用户id
     * @param boardId 板块id
     * @param title 帖子标题
     * @param content 帖子文章
     * @return 统一返回
     */
    @ApiOperation("发布新文章")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                                     @ApiParam("版块id") @RequestParam("boardId") @NonNull Long boardId,
                                     @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                                     @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        //1.检测用户是否被禁言
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //2.封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        //3.调用service层
        articleService.create(article);

        //4.返回结果
        return AppResult.success("发布文章成功");
    }


    /**
     * 获取文章列表（根据参数不同，返回不同的文章列表）
     * @param boardId
     * @return
     */
    @ApiOperation("获取文章")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块id")
                                                    @RequestParam(value = "boardId",required = false)
                                                    Long boardId) {
        List<Article> articles;
        if(boardId != null) {
            articles = articleService.selectAllByBoardId(boardId);
        }else {
            articles = articleService.selectAll();
        }
        //
        if(articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @ApiOperation("获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                        @ApiParam("文章Id") @RequestParam("id") @NonNull Long id) {
        //1.参数校验
        //2.调用service
        Article article = articleService.selectDetailById(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.判断文章是否为当前用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调⽤Service层获取帖⼦详情
        // 当前⽤⼾是否作者
        if (user.getId() == article.getUserId()) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }


    @ApiOperation("更新文章")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("文章id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {

        //1.参数合法性检查
        if(id<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.检查该用户是否被禁言
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.检查文章是否正常
        Article article = articleService.selectById(id);
        if(article==null || article.getDeleteState()==1 ||article.getState()==1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //4.检查登陆用户是否为文章作者
        if(article.getUserId() != user.getId()) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //5.调用service
        articleService.modify(id, title, content);
        return AppResult.success();
    }

    @ApiOperation("点赞操作")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        //1.参数校验
        if(id <= 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.用户检查
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.调用service
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖⼦")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        //1.参数校验


        //2.作者校验
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.文章校验
        Article article = articleService.selectById(id);
        if(article==null || article.getDeleteState()==1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //本人校验
        if(user.getId()!=article.getUserId()) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //4.文章删除--调用service
        articleService.deleteById(id);

        return AppResult.success();
    }

    @ApiOperation("获取用户文章列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                    @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId) {
        if(userId == null) {
            //1.从session中获取userId，说明是当前登陆用户
            log.info("########################进来了");
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }


}
